package chaincode

import (
	"encoding/json"

	"github.com/hyperledger/fabric-chaincode-go/shim"
	"github.com/hyperledger/fabric-protos-go/peer"
)

type SmartContract struct{}

// 初始化
func (s *SmartContract) Init(stub shim.ChaincodeStubInterface) peer.Response {
	return shim.Success(nil)
}

// Invoke
func (s *SmartContract) Invoke(stub shim.ChaincodeStubInterface) peer.Response {
	function, args := stub.GetFunctionAndParameters()
	switch function {
	case "AddAsset":
		return s.AddAsset(stub, args)
	case "QueryAsset":
		return s.QueryAsset(stub, args)
	case "TransferAsset":
		return s.TransferAsset(stub, args)
	default:
		return shim.Error("无方法")
	}
}

// 资产定义
type Asset struct {
	ID    string `json:id`
	Owner string `json:owner`
	Name  string `json:name`
}

// 创建资产
func (s *SmartContract) AddAsset(stub shim.ChaincodeStubInterface, args []string) peer.Response {

	// 申明资产
	asset := Asset{ID: args[0], Owner: args[1], Name: args[2]}

	// JSON
	assetJSON, err := json.Marshal(asset)
	if err != nil {
		shim.Error(err.Error())
	}

	// 存入区块链账本
	stub.PutState(args[0], assetJSON)
	return shim.Success(nil)
}

// 查询资产
func (s *SmartContract) QueryAsset(stub shim.ChaincodeStubInterface, args []string) peer.Response {

	//根据id查询资产
	asset, _ := stub.GetState(args[0])

	return shim.Success(asset)
}

// 转移资产
func (s *SmartContract) TransferAsset(stub shim.ChaincodeStubInterface, args []string) peer.Response {
	//根据id查询资产
	assetJSON, _ := stub.GetState(args[0])
	//反序列化
	var asset Asset
	json.Unmarshal(assetJSON, &asset)
	asset.Owner = args[1]

	updateJSON, _ := json.Marshal(asset)
	stub.PutState(args[0], updateJSON)

	return shim.Success(nil)

}
